package org.mspring.mlog.service;

import javax.transaction.Transactional;

import org.apache.commons.codec.digest.DigestUtils;
import org.mspring.platform.qiniu.QiniuStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qiniu.api.io.PutRet;

/**
 * 微博图片相关服务
 *
 * @author Gao Youbo
 * @since 2014年5月23日
 */
@Service
@Transactional
public class TwitterImageService {

    private static final Logger log = LoggerFactory.getLogger(TwitterImageService.class);

    public static final String TWITTER_IMAGE_PREFIX = "twitter-";

    @Autowired
    private QiniuStorageService qiniuStorageService;

    /**
     * 上传
     *
     * @param bytes
     * @return
     */
    public String upload(byte[] bytes) {
        String key = DigestUtils.md5Hex(bytes);
        key = TWITTER_IMAGE_PREFIX.concat(key);
        try {
            PutRet ret = qiniuStorageService.put(key, bytes);
            if (!ret.ok()) {
                return null;
            }
            return qiniuStorageService.getUrl(ret);
        } catch (Exception e) {
            log.error("上传图片失败", e);
            return null;
        }
    }

    /**
     * 删除
     *
     * @param url
     */
    public void delete(String url) {
        qiniuStorageService.deleteByUrl(url);
    }
}
